package uit.nfcmenu.util;

import java.io.InputStream;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

import uit.nfcmenu.db.model.MenuModel;
import uit.nfcmenu.webservice.EasySSLSocketFactory;
import android.content.Context;
import android.content.res.Configuration;
import android.os.SystemClock;
import android.util.Log;


public class Utilities {
	public static final String tag = Utilities.class.getSimpleName();

	public static void showLogList(String tag, ArrayList<MenuModel> addresses) {
		for (Object address : addresses) {
			Log.i(tag, "address: " + address.toString());
		}
	}

	public static boolean pushCertificateSSL() {
		Log.i(tag, "pushCertificate()");

		TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}

			public void checkClientTrusted(
					java.security.cert.X509Certificate[] certs, String authType) {
			}

			public void checkServerTrusted(
					java.security.cert.X509Certificate[] certs, String authType) {
			}
		} };

		// Install the all-trusting trust manager
		try {
			SSLContext sc = SSLContext.getInstance("SSL");
			// SSLContext sc = SSLContext.getInstance("TLS");
			HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			HttpsURLConnection
					.setDefaultSSLSocketFactory(sc.getSocketFactory());
			HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
		} catch (Exception e) {
			e.printStackTrace();
			Log.w(tag, "pushCertificate() return false");
			return false;
		}
		Log.w(tag, "pushCertificate() return true");
		return true;
	}

	public static void trustEveryoneTLS() {
		Log.i(tag, "trustEveryoneTLS()");
		try {
			HttpsURLConnection
					.setDefaultHostnameVerifier(new HostnameVerifier() {
						public boolean verify(String hostname,
								SSLSession session) {
							return true;
						}
					});
			SSLContext context = SSLContext.getInstance("TLS");
			context.init(null, new X509TrustManager[] { new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return new X509Certificate[0];
				}
			} }, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(context
					.getSocketFactory());
		} catch (Exception e) { // should never happen
			Log.e(tag, "trustEveryoneTLS() error " + e);
		}
	}

	public DefaultHttpClient getDefaultHttpClient() {
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(),
				443));

		HttpParams params = new BasicHttpParams();
		params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
		params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,
				new ConnPerRouteBean(30));
		params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);

		ClientConnectionManager cm = new SingleClientConnManager(params,
				schemeRegistry);
		return new DefaultHttpClient(cm, params);
	}

	// public static boolean pushCertificateTLS() {
	// Log.i(tag, "pushCertificate()");
	// X509TrustManager tm = new X509TrustManager() {
	// public void checkClientTrusted(X509Certificate[] xcs, String string)
	// throws CertificateException { }
	// public void checkServerTrusted(X509Certificate[] xcs, String string)
	// throws CertificateException { }
	// public X509Certificate[] getAcceptedIssuers() { return null; }
	// };
	//
	// // Install the all-trusting trust manager
	// try {
	// SSLContext ctx = SSLContext.getInstance("TLS");
	// ctx.init(null, new TrustManager[]{tm}, null);
	// org.apache.http.conn.ssl.SSLSocketFactory ssf = new
	// org.apache.http.conn.ssl.SSLSocketFactory(truststore)
	//
	// HostnameVerifier hostnameVerifier =
	// org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
	//
	// sc.init(null, trustAllCerts, new java.security.SecureRandom());
	// HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	// HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
	// } catch (Exception e) {
	// e.printStackTrace();
	// Log.w(tag, "pushCertificate() return false");
	// return false;
	// }
	// Log.w(tag, "pushCertificate() return true");
	// return true;
	// }

	public static void changeLanguage(Context context, String language) {
		Log.i(tag, "changeLanguage(" + context.getClass().getSimpleName() + "," + language + ")");
		try {
			Locale locale = new Locale(language);
			Locale.setDefault(locale);
			Configuration config = new Configuration();
			config.locale = locale;
			context.getResources().updateConfiguration(config,
					context.getResources().getDisplayMetrics());
		} catch (Exception e) {
			// e.printStackTrace();
		}
	}

	/*
	 * timer
	 */
	// "Wed, 12 Sep 2012 02:41:19 GMT "
	public static Date parsefromString(String date) { // FIXME: change date format
		String FORMAT_DAY = "EEE, dd MMM yyyy hh:mm:ss zzz";
		DateFormat datef = new SimpleDateFormat(FORMAT_DAY);
		try {
			return datef.parse(date);
		} catch (Exception e) {
			return null;
		}
//		return new Date(date);
	}
	
//	public static String getTimeToCurrent(String string){
//		Log.e(tag, "getTimeToCurrent("+string+")");
//        String FORMAT_DAY_INPUT = "EEE MMM dd HH:mm:ss zzz yyyy";
////        String FORMAT_DAY_OUTPUT = "HH:mm:ss";
//        
//		DateFormat dateInput = new SimpleDateFormat(FORMAT_DAY_INPUT);
////		DateFormat dateOutput = new SimpleDateFormat(FORMAT_DAY_OUTPUT);
//        try { // java.text.ParseException: Unparseable date: "Thu Mar 01 10:15:52 UTC 2012"
//            Date start = dateInput.parse(string);
//            long seconds = (System.currentTimeMillis() - start.getTime()) / 1000;
//            long minutes = (long) (seconds/60);
//            long hours = minutes / 60;
//            long days = hours / 24;
////            Log.i(tag, "1: day="+days+" h="+hours+" m="+minutes+" s="+seconds);
//            seconds = (seconds - (minutes*60));
//            minutes = (minutes - (hours*60));
//            hours = (hours-(24*days));
////            Log.i(tag, "2: day="+days+" h="+hours+" m="+minutes+" s="+seconds);
////            return ""+hours+":"+minutes+":"+seconds;
//            return ((String.valueOf(hours).length() == 1) ? "0" + hours : hours) + 
//            		":" + ((String.valueOf(minutes).length() == 1) ? "0" + minutes : minutes);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "";
//    } 
	
	// "Wed, 12 Sep 2012 02:41:19 GMT "
//	public static String getDateinTimeZone(String string) {
//		if (string == null) {
//			return "";
//		}
//		String FORMAT_DAY = "EEE, dd MMM yyyy hh:mm:ss zzz ";
//		String FORMAT_DAY2 = "dd-MM-yyyy HH:mm:ss";
//		DateFormat datef = new SimpleDateFormat(FORMAT_DAY);
//		DateFormat datef2 = new SimpleDateFormat(FORMAT_DAY2);
//		try {// java.text.ParseException: Unparseable date:
//				// "Thu Mar 01 10:15:52 UTC 2012"
//			Date start = datef.parse(string);
//			String kq = datef2.format(start);
//
//			return kq;
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return string.substring(10, 19);
//	}

	public static long getTimeCurrentCounter(Date date) {

		try { // java.text.ParseException: Unparseable date:

			long seconds = (System.currentTimeMillis() - date.getTime());
			return SystemClock.elapsedRealtime() - seconds;
		} catch (Exception e) {
			return 0;
		}
	}

	public static String getStringNotNull(String text) {
		if (text == null || CommConstant.SIGN_NULL.endsWith(text)){
			return "";
		}
		return text;
	}

	public static String convertStreamToString(InputStream is) { 
		try {
	        return new java.util.Scanner(is).useDelimiter("\\A").next();
	    } catch (java.util.NoSuchElementException e) {
	        return "";
	    }
	}

	public static String portTimeToString(long temp) {
		String time;
		int h = (int) temp / 3600;
		int min = (int) temp / 60 - h * 60;
		time = ((h > 0) ? h + ":" : "00:")
				+ ((min < 10) ? "0" + min : min)
				/*+ ":" + ((sec < 10) ? "0" + sec : sec)*/;
		return time;
	}

//	public static String getTimeToCurrent(String string) {
//		String FORMAT_DAY_INPUT = "EEE MMM dd HH:mm:ss zzz yyyy";
//		// String FORMAT_DAY_OUTPUT = "HH:mm:ss";
//
//		DateFormat dateInput = new SimpleDateFormat(FORMAT_DAY_INPUT);
//		// DateFormat dateOutput = new SimpleDateFormat(FORMAT_DAY_OUTPUT);
//		try { // java.text.ParseException: Unparseable date:
//				// "Thu Mar 01 10:15:52 UTC 2012"
//			Date start = dateInput.parse(string);
//			long seconds = (System.currentTimeMillis() - start.getTime()) / 1000;
//			long minutes = (long) (seconds / 60);
//			long hours = minutes / 60;
//			long days = hours / 24;
//			// Log.i(tag,
//			// "1: day="+days+" h="+hours+" m="+minutes+" s="+seconds);
//			seconds = (seconds - (minutes * 60));
//			minutes = (minutes - (hours * 60));
//			hours = (hours - (24 * days));
//			// Log.i(tag,
//			// "2: day="+days+" h="+hours+" m="+minutes+" s="+seconds);
//			// return ""+hours+":"+minutes+":"+seconds;
//			return ((String.valueOf(hours).length() == 1) ? "0" + hours : hours)
//					+ ":"
//					+ ((String.valueOf(minutes).length() == 1) ? "0" + minutes
//							: minutes);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return "";
//	}

	// =============== Image Handler />
	/*
	 * Convert
	 */

	// public static ArrayList<IModel> convertToIterface(
	// IModel[] selectItems) {
	// ArrayList<IModel> addressStrings = new ArrayList<IModel>();
	// for (IModel address : selectItems) {
	// addressStrings.add((IModel)address);
	// }
	// return addressStrings;
	// }
	//
	// public static ArrayList<IModel> convertToIterface(
	// ArrayList<ItemModel> selectItems) {
	// ArrayList<IModel> addressStrings = new ArrayList<IModel>();
	// for (IModel address : selectItems) {
	// addressStrings.add((IModel)address);
	// }
	// return addressStrings;
	// }

	// public static ArrayList<IModel> convertToIterface(
	// ArrayList<OrderModel> selectItems) {
	// ArrayList<IModel> addressStrings = new ArrayList<IModel>();
	// for (IModel address : selectItems) {
	// addressStrings.add((IModel)address);
	// }
	// return addressStrings;
	// }
}
